//
//  AppDelegate.m
//  ShellWallert
//
//  Created by lvzhao on 2019/5/13.
//  Copyright © 2019 吕VV. All rights reserved.
//

#import "AppDelegate.h"
#import "ShellLaunchViewController.h"
#import "IQKeyboardManager.h"
#import "WHDebugToolManager.h"
#import <Bugly/Bugly.h>
#import "ShellWallertManager.h"
#import "LZBaseTabBarViewController.h"


// 引入 JPush 功能所需头文件
#import "JPUSHService.h"
// iOS10 注册 APNs 所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif



@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = UIColor.whiteColor;
    //本地操作
    [self initLocalData];
    
    [self reginsterApplication:application withOptions:launchOptions];
    //启动页
    ShellLaunchViewController *launchVC = [[ShellLaunchViewController alloc]init];
    self.window.rootViewController = launchVC;
    

    [self.window makeKeyAndVisible];

    
    if (launchOptions) {
        //到首页推送
        [LZToolCache setBool:YES forKey:@"isNotification"];
    }
    
    return YES;
}


#pragma mark - 本地操作
- (void)initLocalData{
    [self IQKeyboardConfig];
    
    [kShellLanguageManager initUserLanguage];
    
    
   
    //操作一下
#ifdef DEBUG
    [LZNetworkingManager setAutoLog:YES];

    //查看log
    [[WHDebugToolManager sharedInstance] toggleWith:DebugToolTypeAll];
    
    //    如果不需要显示GHConsole 你可以使用 [[GHConsole sharedConsole] stopPrinting]   或者直接把启动方法注释掉即可， 谢谢。
    [[GHConsole sharedConsole] startPrintLog];
    
    
#else
    [LZNetworkingManager setAutoLog:NO];

    [Bugly startWithAppId:@"b108c6d225"];

#endif
  
}

//远程推送
- (void)reginsterApplication:(UIApplication *)application withOptions:(NSDictionary *)launchOptions{
    
    
    //极光推送
   // 3.0.0及以后版本注册
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    if (@available(iOS 12.0, *)) {
      entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
    } else {
      entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    }
   
   [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];

    BOOL Production = NO;
    
        //操作一下
    #ifdef DEBUG
         Production = NO;
    #else
        Production = YES;

    #endif
    
  
   //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:k_JpushKey
                          channel:@"生产"
                 apsForProduction:Production
            advertisingIdentifier:nil];

    //2.1.9版本新增获取registration id block接口。
     [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
       if(resCode == 0){
         NSLog(@"registrationID获取成功：%@",registrationID);

       }
       else{
         NSLog(@"registrationID获取失败，code：%d",resCode);
       }
     }];
}

// 配置键盘库
- (void)IQKeyboardConfig{
    
    [IQKeyboardManager sharedManager].enable = YES;                             //使用IQKeyboard
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;                   // 控制是否显示键盘上的工具条
    [IQKeyboardManager sharedManager].toolbarDoneBarButtonItemText = @"Done";
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;         //当键盘弹起时，点击背景收起键盘
    [IQKeyboardManager sharedManager].shouldShowToolbarPlaceholder = YES;       // 是否显示占位文字
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {

    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];

}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    [[ShellWallertManager sharedInstance] checkVersion:YES];
    
    [application setApplicationIconBadgeNumber:0];
     [application cancelAllLocalNotifications];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application
    didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"deviceToken === : %@", deviceToken);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
           /// Required - 注册 DeviceToken
           [JPUSHService registerDeviceToken:deviceToken];
       });
       [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
           NSLog(@"resCode : %d,registrationID: %@",resCode,registrationID);
       }];
}

//iOS8-10
- (void)application:(UIApplication *)application
    didReceiveRemoteNotification:(NSDictionary *)userInfo
          fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  [JPUSHService handleRemoteNotification:userInfo];
  NSLog(@"iOS7及以上系统，收到通知:%@", userInfo );
 
  completionHandler(UIBackgroundFetchResultNewData);
}


#pragma mark- JPUSHRegisterDelegate
//iOS10新增：处理前台收到通知的代理方法
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler  API_AVAILABLE(ios(10.0)){
  // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
            NSLog(@"willPresentNotification === iOS10 前台收到远程通知:%@", userInfo);
            LZBaseTabBarViewController *tabBarController = (LZBaseTabBarViewController *)LZTool.currentViewController.tabBarController;
            tabBarController.selectedIndex = 1;

        }
    } else {
        // Fallback on earlier versions
    }
  completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

 //iOS10新增：处理后台点击通知的代理方法
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
  // Required
   NSDictionary * userInfo = response.notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
            NSLog(@"从后台进入appdidReceiveNotificationResponse === iOS10 前台收到远程通知:%@", userInfo);
            LZBaseTabBarViewController *tabBarController = (LZBaseTabBarViewController *)LZTool.currentViewController.tabBarController;
            tabBarController.selectedIndex = 1;
            
        }
    } else {
        // Fallback on earlier versions
    }
  completionHandler();  // 系统要求执行这个方法
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

  // Required, For systems with less than or equal to iOS 6
  [JPUSHService handleRemoteNotification:userInfo];
}

@end
